var redis = require('redis');
var config = require('../config');

// 缓存 redis
var client = redis.createClient(config.redis.port, config.redis.host);

module.exports = {
  // 获取数据
  get: function (key) {
    return new Promise(function (resolve, reject) {
      client.hget('kncache', key, function (error, reply) {
        if (error) {
          return reject(error);
        }
        try {
          reply = JSON.parse(reply);
        }
        catch (e) {
          reply = reply;
        }
        finally {
          return resolve(reply);
        }
      });
    });
  },

  // 设置数据
  set: function (key, value) {
    return new Promise(function (resolve, reject) {
      client.hset('kncache', key, JSON.stringify(value), function (error, result) {
        if (error) {
          return reject(error);
        }
        // 设置1小时过期
        client.expire('kncache', 3600);
        return resolve(result);
      });
    });
  },
};